#include <stdlib.h>
#include <math.h>

#include <imp/imp_common.h>
#include <imp/imp_algo.h>
#ifdef DMALLOC
#include <imp/dmalloc.h>
#endif
int IMP_ALGO_BoolFilter(int *filter, bool val, int thresd)
{
	*filter = (val == true) ? *filter + 1 : *filter - 1;
	*filter = (*filter > 2 * thresd + 2) ? (2 * thresd + 2)
		: ((*filter < -1 * thresd - 2) ? -1 * thresd - 2 : *filter);
	return (*filter > 0) ? 1 : ((*filter < -1 * thresd) ? -1 : 0);
}

int IMP_ALGO_RectFilter(IMPRect rect, int area)
{
	return (abs(rect.p0.x - rect.p1.x) * abs(rect.p0.y - rect.p1.y) > 0) ? 1 : 0;
}

int IMP_ALGO_RectMatch(IMPRect oldRect, IMPRect curRect, MatchThresd posThresd,
		MatchThresd sizeThresd)
{
	uint8_t p = 0, s = 0;
	int pxo = 0, pyo = 0, pxc = 0, pyc = 0, pd = 0;
	int sx0 = 0, sy0 = 0, sx1 = 0, sy1 = 0, sd = 0;

	/* position */
	pxo = (oldRect.p0.x + oldRect.p1.x) / 2;
	pyo = (oldRect.p0.y + oldRect.p1.y) / 2;
	pxc = (curRect.p0.x + curRect.p1.x) / 2;
	pyc = (curRect.p0.y + curRect.p1.y) / 2;
	pd = sqrt((pxc - pxo) * (pxc - pxo) + (pyc - pyo) * (pyc - pyo));
	if (pd < posThresd.shakeThresd) {
		p = ALGO_MATCH_SHAKE_VAL;
	} else if (pd < posThresd.changeThresd) {
		p = ALGO_MATCH_CHANGE_VAL;
	} else {
		p = ALGO_MATCH_INV_VAL;
	}

	sx0 = curRect.p0.x - oldRect.p0.x;
	sy0 = curRect.p0.y - oldRect.p0.y;
	sx1 = curRect.p1.x - oldRect.p1.x;
	sy1 = curRect.p1.y - oldRect.p1.y;
	sd = sqrt(sx0 * sx0 + sy0 * sy0) + sqrt(sx1 * sx1 + sy1 * sy1);

	if (sd < sizeThresd.shakeThresd) {
		s = ALGO_MATCH_SHAKE_VAL;
	} else if (sd < sizeThresd.changeThresd) {
		s = ALGO_MATCH_CHANGE_VAL;
	} else {
		s = ALGO_MATCH_INV_VAL;
	}

	if (ALGO_MATCH_INV(p, s)) {
		return -1;
	} else if (ALGO_MATCH_SHAKE(p, s)) {
		return 0;
	} else if (ALGO_MATCH_CHANGE(p, s)) {
		return 1;
	}

	return -1;
}
